<template>
  <basic-container>
    <avue-tabs :option="tabOption" style="margin: 0 10px" @change="handleTabClick"> </avue-tabs>
    <div v-if="tabType.prop == 'workSection'">
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :defaults.sync="defaults"
        :page.sync="page"
        :permission="permissionList"
        v-model="form"
        ref="crud"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="menuRight">
          <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" size="small" plain icon="el-icon-plus" @click="handleAddSection">新 增</el-button>
        </template>
        <template slot-scope="{ row }" slot="menu">
          <el-button type="text" size="small" icon="el-icon-view" plain @click="handleView(row)" style="border: 0 !important">详情</el-button>
          <el-button type="text" size="small" icon="el-icon-edit" plain @click="handleEdit(row)" style="border: 0 !important">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" plain @click="handleDelete(row)" style="border: 0 !important">删除</el-button>
        </template>
      </avue-crud>
    </div>
    <div v-if="tabType.prop == 'productSection'">
      <ProductSectionDefinition v-if="tabType.prop == 'productSection'"></ProductSectionDefinition>
    </div>
    <el-dialog
      ref="dialog"
      :title="addSection.title"
      width="80%"
      custom-class="addSectionDialog"
      append-to-body
      :visible.sync="addSection.visible"
      @close="handleCloseSectionDialog"
      :close-on-click-modal="false"
    >
      <div class="sectionArea" v-loading="addSection.loading">
        <div class="dispatch-title">
          <div class="dispatch-title-dot"></div>
          <div class="dispatch-title-text">工段信息</div>
        </div>
        <avue-form
          ref="form"
          class="workInfoForm"
          v-model="addSection.form"
          :option="addSection.option"
          @submit="handleSubmitSection"
          @reset-change="handleUndoReset"
        ></avue-form>
        <div class="dispatch-title">
          <div class="dispatch-title-dot"></div>
          <div class="dispatch-title-text" v-if="addSection.title == '详情'">绑定产线</div>
          <div class="dispatch-title-text" v-else>产线配置</div>
        </div>
        <avue-crud :option="addSection.line.option" :data="addSection.line.data">
          <template slot-scope="{ row }" slot="menu">
            <el-button type="text" size="small" icon="el-icon-delete" plain @click="handleUnBind(row)" style="border: 0 !important">解绑</el-button>
          </template>
          <template slot="menuLeft">
            <el-button type="primary" size="mini" plain icon="el-icon-plus" v-if="addSection.title != '详情'" @click="handleSelectLine">选择产线</el-button>
          </template>
        </avue-crud>
        <div class="dispatch-title">
          <div class="dispatch-title-dot"></div>
          <div class="dispatch-title-text">作业配置</div>
        </div>
        <avue-form ref="workConfigForm" class="workConfigForm" v-model="addSection.workConfig.form" :option="addSection.workConfig.option"> </avue-form>

        <div class="weekdayItem" v-for="(item, index) in addSection.workConfig.form.weekdays" :key="index">
          <div class="weekday">
            <div class="weekday-label">星期选择:</div>
            <el-select size="small" disabled multiple collapse-tags v-model="item.weekday" placeholder="请选择星期">
              <el-option label="周一" value="MONDAY"></el-option>
              <el-option label="周二" value="TUESDAY"></el-option>
              <el-option label="周三" value="WEDNESDAY"></el-option>
              <el-option label="周四" value="THURSDAY"></el-option>
              <el-option label="周五" value="FRIDAY"></el-option>
              <el-option label="周六" value="SATURDAY"></el-option>
              <el-option label="周日" value="SUNDAY"></el-option>
            </el-select>
          </div>
          <div class="workHour">
            <div class="workHour-label">作业工时(H):</div>
            <div class="hour">{{ item.workHour }}</div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="handleCloseSectionDialog()">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" v-if="addSection.title != '详情'" @click="$refs.form.submit()" v-preventReClick
          >保 存</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      ref="dialog"
      title="选择产线"
      width="70%"
      append-to-body
      custom-class="selectLineDialog"
      :visible.sync="showDialog"
      v-if="showDialog"
      @close="closeSelectLineDialog"
      :close-on-click-modal="false"
    >
      <data class="selectLineArea">
        <avue-crud
          class="leftCrud"
          :key="timer"
          :option="transferOption"
          :data="leftLine.data"
          :table-loading="leftLine.loading"
          v-model="leftLine.form"
          ref="leftCrud"
          @selection-change="selectionLeftChange"
          @search-change="search"
          @on-load="getSelectLineRequest"
        >
          <template slot="menuLeft">
            <el-button type="text"><span class="title">产线列表：</span></el-button>
          </template>
        </avue-crud>

        <div class="el-transfer-button">
          <el-button type="primary" icon="el-icon-arrow-left" :disabled="rightSelectionList.length <= 0" class="btn" @click="moveToLeft"></el-button>
          <el-button type="primary" icon="el-icon-arrow-right" :disabled="leftSelectionList.length <= 0" class="btn" @click="moveToRight"></el-button>
        </div>

        <avue-crud class="rightCrud" :key="timer + 10000" :option="rightTransferOption" :data="rightData" ref="rightCrud" @selection-change="selectionRightChange">
          <template slot="menuLeft">
            <el-button type="text"><span class="title">已选中列表：</span></el-button>
          </template>
        </avue-crud>
      </data>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="closeSelectLineDialog">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleSaveLine" v-preventReClick>保 存</el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, add, checkSection, getDetail, getSelectLine, removeSection, getCalendarDetail, getCalendarDayTemplateDetail } from '@/api/product/sectionDefinition';
import { initCalendar } from '@/api/product/productCalendar.js';
import { mapGetters } from 'vuex';
import ProductSectionDefinition from '@/views/product/productSectionDefinition.vue';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
export default {
  components: {
    userTableConfig,
    CommonModalTemplate,
    ProductSectionDefinition
  },
  data() {
    return {
      pageCode: 'sectionDefinition',
      tabType: {},
      tabOption: {
        column: [
          {
            label: '生产工段',
            prop: 'workSection'
          },
          {
            label: '产品工段',
            prop: 'productSection'
          }
        ]
      },
      visible: false,
      tableOption: {},
      form: {},
      data: [],
      leftLine: {
        loading: false,
        form: {},
        query: {},
        data: []
      },
      rightData: [],
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      addSection: {
        title: '新增',
        visible: false,
        loading: false,
        form: {},
        option: {
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 120,
          detail: false,
          column: [
            {
              label: '生产工段编码',
              prop: 'code',
              span: 12,
              rules: [
                {
                  required: true,
                  message: '请输入生产工段编码',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '生产工段名称',
              prop: 'name',
              span: 12,
              rules: [
                {
                  required: true,
                  message: '请输入生产工段名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '创建人',
              prop: 'createUserName',
              display: true,
              span: 12
            },
            {
              label: '创建时间',
              prop: 'createTime',
              display: true,
              span: 12
            },
            {
              label: '备注',
              prop: 'remark',
              type: 'textarea',
              overHidden: true,
              span: 24,
              minRows: 3,
              maxRows: 3
            }
          ]
        },
        line: {
          data: [],
          option: {
            height: '200px',
            tip: false,
            searchShow: true,
            searchSpan: 5,
            searchMenuSpan: 4,
            labelWidth: 110,
            searchLabelWidth: 110,
            dialogCustomClass: 'custom-class',
            border: true,
            index: true,
            indexLabel: '序号',
            addBtn: false,
            viewBtn: false,
            editBtn: false,
            delBtn: false,
            refreshBtn: false,
            excelBtn: false,
            selection: false,
            dialogDrag: false, // 开启拖拽功能
            dialogClickModal: false,
            rowKey: 'id',
            nodeKey: 'id',
            columnBtn: false,
            menu: true,
            menuWidth: 100,
            column: [
              {
                label: '产线编码',
                prop: 'lineCode'
              },
              {
                label: '产线名称',
                prop: 'lineName'
              },
              {
                label: '所属车间',
                prop: 'workshopName'
              },
              {
                label: '产线状态',
                prop: 'status',
                type: 'select',
                dicData: [
                  {
                    label: '待产',
                    value: 1
                  },
                  {
                    label: '生产',
                    value: 2
                  },
                  {
                    label: '停线',
                    value: 3
                  }
                ]
              }
            ]
          }
        },
        workConfig: {
          form: {},
          option: {
            submitBtn: false,
            emptyBtn: false,
            labelWidth: 120,
            column: [
              {
                label: '日历方案',
                prop: 'name',
                span: 12,
                disabled: true,
                type: 'search',
                appendClick: () => {
                  this.openCalendar();
                }
              },
              {
                label: '日历编码',
                prop: 'code',
                disabled: true,
                span: 12
              },
              {
                label: '开始时间',
                prop: 'fromDate',
                type: 'date',
                valueFormat: 'yyyy-MM-dd',
                disabled: true,
                span: 12
              },
              {
                label: '结束时间',
                prop: 'toDate',
                type: 'date',
                valueFormat: 'yyyy-MM-dd',
                disabled: true,
                span: 12
              },
              {
                label: '作业时间方案',
                prop: 'defaultWorkingDay',
                disabled: true,
                span: 24
              }
            ]
          }
        }
      },
      oldCalendarData: {}, //保存旧日历方案信息
      calendarData: {},
      selectionList: [],
      rightSelectionList: [],
      leftSelectionList: [],
      showDialog: false,
      option: {
        height: 'calc(100vh - 420px)',
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        labelWidth: 110,
        searchLabelWidth: 100,
        dialogCustomClass: 'custom-class',
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        delBtn: false,
        expanded: true,
        refreshBtn: true,
        excelBtn: false,
        selection: true,
        dialogDrag: false, // 开启拖拽功能
        dialogClickModal: false,
        columnBtn: false,
        menuWidth: 200,
        column: [
          {
            label: '生产工段编码',
            prop: 'code',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            rules: [
              {
                required: true,
                message: '请输入生产工段编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '生产工段名称',
            prop: 'name',
            search: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            rules: [
              {
                required: true,
                message: '请输入生产工段名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            slot: true,
            type: 'textarea',
            overHidden: true,
            minRows: 3,
            maxRows: 3,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: '创建人',
            prop: 'createUserName',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: '创建时间',
            prop: 'createTime',
            width: 150,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          }
        ]
      },
      transferOption: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchBtn: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        height: '400px',
        dialogClickModal: false,
        border: true,
        columnBtn: false,
        emptyBtn: false,
        viewBtn: false,
        addBtn: false,
        selection: true,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: false,
        searchSpan: 5,
        menu: false,
        refreshBtn: false,
        selectable: (row, index) => {
          return !this.addSection.line.data.map((item) => item.lineId).includes(row['id']) && !row.sectionId;
        },
        column: [
          {
            label: '产线编码',
            prop: 'code',
            searchSpan: 12,
            search: true
          },
          {
            label: '产线名称',
            prop: 'name'
          },
          {
            label: '所属车间',
            prop: 'workshopName'
          },
          {
            label: '所属工段',
            prop: 'sectionName'
          }
        ]
      },
      rightTransferOption: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchBtn: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        height: '400px',
        dialogClickModal: false,
        border: true,
        columnBtn: false,
        emptyBtn: false,
        viewBtn: false,
        addBtn: false,
        selection: true,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: false,
        searchSpan: 5,
        menu: false,
        refreshBtn: false,
        column: [
          {
            label: '产线编码',
            prop: 'code',
            searchSpan: 12,
            search: true
          },
          {
            label: '产线名称',
            prop: 'name'
          },
          {
            label: '所属车间',
            prop: 'workshopName'
          }
        ]
      },
      infoForm: {},
      infoOption: {
        selection: false,
        editBtn: false,
        height: 270,
        border: true,
        menuWidth: 150,
        addBtn: false,
        delBtn: true,
        delBtnText: '解绑',
        menu: true,
        columnBtn: false,
        refreshBtn: false,
        index: true,
        indexLabel: '序号',
        tip: false,
        column: [
          {
            label: '产线编码',
            prop: 'code'
          },
          {
            label: '产线名称',
            prop: 'name'
          },
          {
            label: '所属车间',
            prop: 'workshopName'
          },
          {
            label: '产线状态',
            prop: 'status',
            type: 'select',
            html: true,
            dicData: [
              {
                label: '待产',
                value: 1
              },
              {
                label: '生产',
                value: 2
              },
              {
                label: '停线',
                value: 3
              }
            ]
          },
          {
            label: '创建时间',
            prop: 'createTime',
            hide: true
          }
        ]
      },
      infoData: [],
      modalName: '',
      timer: new Date().getTime()
    };
  },
  mounted() {
    this.tabType = this.tabOption.column[0];
    this.$nextTick(() => {
      console.log(this.tabType);
      this.$structuralSplit(this.tabType.label);
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.pallet_add, false),
        // viewBtn: this.vaildData(this.permission.pallet_view, false),
        // delBtn: this.vaildData(this.permission.pallet_delete, false),
        // editBtn: this.vaildData(this.permission.pallet_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    isDisabled() {
      return this.data.some((item) => {
        return item.$cellEdit || !item.id;
      });
    },
    isSaveDisabled() {
      return this.data.some((item) => {
        return item.$cellEdit;
      });
    }
  },
  methods: {
    // 打开 选择产线弹框
    handleSelectLine() {
      this.leftLine.data = [];
      this.rightData = [];
      this.leftLine.form = {};
      this.showDialog = true;
    },
    handleSubmitSection(form, done) {
      const that = this;
      let lineSectionList = that.addSection.line.data.map((item) => {
        return {
          lineId: item.lineId,
          lineCode: item.lineCode,
          lineName: item.lineName
        };
      });
      form.lineSectionList = lineSectionList;
      if (that.addSection.title == '新增') {
        that.handleSubmitAddSection(form, done);
      } else {
        that.handleSubmitEditSection(form, done);
      }
    },
    async handleSubmitAddSection(form, done) {
      const that = this;
      delete form.id;
      try {
        let result = await add(form);
        let sectionId = result.data.data;
        if (that.addSection.workConfig.form.id) {
          let params = that.calendarData;
          params.addSection = JSON.stringify({
            sectionId: sectionId,
            sectionCode: form.code,
            sectionName: form.name
          });
          // 修改日作业方案工段
          await initCalendar(params);
        }
        that.$message({
          type: 'success',
          message: '操作成功!'
        });
        that.onLoad(that.page);
        that.addSection.visible = false;
      } catch (error) {
      } finally {
        done();
      }
    },
    async handleSubmitEditSection(form, done) {
      const that = this;
      try {
        let result = await add(form);
        let sectionId = result.data.data;
        let oldId = that.oldCalendarData.id;
        let newId = that.addSection.workConfig.form.id;
        let newCalendarParams = structuredClone(that.calendarData);
        newCalendarParams.addSection = JSON.stringify({
          sectionId: sectionId,
          sectionCode: form.code,
          sectionName: form.name
        });
        console.log(newCalendarParams);
        // 已配置日历方案
        if (newId && newCalendarParams.id) {
          if (!oldId) {
            await initCalendar(newCalendarParams); // 修改日作业方案工段
          } else if (oldId && newId != oldId) {
            // 已修改和之前不一致
            let msg = `${form.name}已有日作业方案为${that.oldCalendarData.name}，请确定是否要修改？`;
            const confirmResult = await this.$confirm(msg, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });
            if (confirmResult) {
              await initCalendar(newCalendarParams); // 修改日作业方案工段
            }
          }
        }
        done();
        that.$message({
          type: 'success',
          message: '操作成功!'
        });
        that.onLoad(that.page);
        that.addSection.visible = false;
      } catch (error) {
      } finally {
        done();
      }
    },
    handleTabClick(column) {
      this.tabType = column;
      this.$nextTick(() => {
        this.$structuralSplit(this.tabType.label);
      });
    },
    //新增生产工段
    handleAddSection() {
      this.addSection.title = '新增';
      this.addSection.visible = true;
      this.addSection.line.data = [];
      this.addSection.option.detail = false;
      this.addSection.line.option.menu = true;
      this.addSection.workConfig.form.id = '';
      this.oldCalendarData = {};
      this.handelFieldDisplay(false);
    },
    handleEdit(row) {
      this.addSection.title = '编辑';
      this.addSection.line.option.menu = true;
      this.handleSectionInfo(row.id);
      this.handelFieldDisplay(false);
    },
    handleView(row) {
      this.addSection.title = '详情';
      this.addSection.line.option.menu = false;
      this.handleSectionInfo(row.id);
      this.handelFieldDisplay(true);
    },
    handelFieldDisplay(display) {
      let createUserNameColumnIndex = this.addSection.option.column.findIndex((item) => item.prop == 'createUserName');
      let createTimeColumnIndex = this.addSection.option.column.findIndex((item) => item.prop == 'createTime');
      this.addSection.option.column[createUserNameColumnIndex].display = display;
      this.addSection.option.column[createTimeColumnIndex].display = display;
    },
    handleSectionInfo(id) {
      this.addSection.loading = true;
      this.addSection.visible = true;
      this.addSection.option.detail = this.addSection.title == '详情';
      Promise.all([getDetail(id), getCalendarDetail(id)])
        .then(([dataA, dataB]) => {
          console.log(dataA, dataB);
          let sectionDetailData = dataA.data.data;

          this.addSection.form.id = sectionDetailData.id;
          this.addSection.form.code = sectionDetailData.code;
          this.addSection.form.name = sectionDetailData.name;
          this.addSection.form.remark = sectionDetailData.remark;
          this.addSection.line.data = sectionDetailData.lineSectionList;

          let workConfigData = dataB.data.data;
          if (workConfigData) {
            this.addSection.workConfig.form = workConfigData;
            this.oldCalendarData = structuredClone(workConfigData);
            let defaultWorkingDay = JSON.parse(workConfigData.defaultWorkingDay || '{}');
            this.addSection.workConfig.form.defaultWorkingDay = defaultWorkingDay.schemeName;
            return workConfigData.calendarTimeSchemeId;
          }
        })
        .then((calendarTimeSchemeId) => {
          getCalendarDayTemplateDetail(calendarTimeSchemeId).then((res) => {
            let data = res.data.data;
            if (data && data.details) {
              let details = data.details;
              details.forEach((item) => {
                item.weekday = item.weekday.split(',');
              });
              this.$set(this.addSection.workConfig.form, 'weekdays', details);
            }
          });
        })
        .finally(() => {
          this.addSection.loading = false;
        });
    },
    handleCloseSectionDialog() {
      this.$refs.form.resetForm();
      this.$refs.workConfigForm.resetForm();
      this.addSection.visible = false;
      this.oldCalendarData = {};
    },
    closeSelectLineDialog() {
      this.leftSelectionList = [];
      this.rightSelectionList = [];
      this.leftLine.query = {};
      this.showDialog = false;
    },
    // 选择产线 保存
    handleSaveLine() {
      let flag = false;
      let selection = this.rightSelectionList.length > 0 ? this.rightSelectionList : this.rightData;
      selection.forEach((item) => {
        item.lineCode = item.code;
        item.lineName = item.name;
        item.lineId = item.id;
      });
      this._uniqWith(this.addSection.line.data.concat(selection), (arrVal, othVal) => {
        if (arrVal.lineCode === othVal.lineCode && arrVal.lineName === othVal.lineName) {
          flag = true;
        }
      });

      if (flag) {
        this.$message({
          type: 'warning',
          message: '当前和已选有重复，请重新选择!'
        });
        return;
      }
      this.addSection.line.data = this.addSection.line.data.concat(selection);
      this.leftLine.query = {};
      this.showDialog = false;
    },
    search(params, done) {
      this.leftLine.query = params;
      this.getSelectLineRequest();
      done();
    },
    handleLineConfig(row) {
      this.newKey();
      this.leftLine.data = [];
      this.rightData = [];
      this.leftLine.form = {};
      this.showDialog = true;
      this.getSelectLineRequest();
    },
    getSelectLineRequest() {
      this.leftLine.loading = true;
      getSelectLine(this.leftLine.query)
        .then((res) => {
          let data = this._get(res, 'data.data', []);
          this.leftLine.data = data;
        })
        .finally(() => {
          this.leftLine.loading = false;
        });
    },
    async handleUnBind(row) {
      let checkData = await checkSection(row.sectionId, row.lineId);
      if (checkData.data.data !== 'true') {
        this.$message.error(checkData.data.data);
        return;
      }
      let msg = `是否确认将产线${row.lineName}从工段 ${row.sectionName}中解绑？`;
      let confirmStatus = await this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (confirmStatus) {
        let index = this.addSection.line.data.findIndex((item) => item.lineId === row.lineId);
        this.addSection.line.data.splice(index, 1);
        this.addSection.line.data = this._cloneDeep(this.addSection.line.data);
        console.log(this.addSection.line.data, 'this.addSection.line.data');
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionLeftChange(list) {
      this.leftSelectionList = list;
    },
    selectionRightChange(list) {
      this.rightSelectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /*
     * 移至左边
     */
    moveToLeft() {
      this.rightData = this._differenceWith(this.rightData, this.rightSelectionList, (item1, item2) => {
        return item1.name === item2.name && item1.code === item2.code;
      });
      this.selectionClear();
    },
    /*
     * 移至右边
     */
    moveToRight() {
      let flag = false;
      this._uniqWith(this.leftSelectionList.concat(this.rightData), (arrVal, othVal) => {
        if (arrVal.code === othVal.code && arrVal.name === othVal.name) {
          flag = true;
        }
      });

      if (flag) {
        this.$message({
          type: 'warning',
          message: '当前和已选有重复，请重新选择!'
        });
        return;
      }
      this.rightData = this.rightData.concat(this.leftSelectionList);
      this.selectionClear();
    },
    handleDelete(row) {
      this.$confirm(`是否确认将${row.name}工段删除?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return removeSection(row.id)
          .then((result) => {
            this.$message.success(result.data.msg);
            this.onLoad(this.page);
          })
          .catch(() => {});
      });
    },
    /**
     * 公共模态框选中的值
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'calendarModal':
          this.calendarData = rowData;
          this.addSection.workConfig.form.id = rowData.id;
          this.addSection.workConfig.form.name = rowData.name;
          this.addSection.workConfig.form.code = rowData.code;
          this.addSection.workConfig.form.fromDate = rowData.fromDate;
          this.addSection.workConfig.form.toDate = rowData.toDate;
          let defaultWorkingDay = JSON.parse(rowData.defaultWorkingDay || '{}');
          this.addSection.workConfig.form.defaultWorkingDay = defaultWorkingDay.schemeName;
          let calendarTimeSchemeId = rowData.calendarTimeSchemeId;
          getCalendarDayTemplateDetail(calendarTimeSchemeId).then((res) => {
            let data = res.data.data;
            if (data && data.details) {
              let details = data.details;
              details.forEach((item) => {
                item.weekday = item.weekday.split(',');
              });
              this.$set(this.addSection.workConfig.form, 'weekdays', details);
            }
          });
          break;
        default:
          break;
      }
    },
    openCalendar() {
      this.modalName = 'calendarModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择日作业方案（双击进行选择）',
        url: '/api/mes-product/calendar/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '日历方案',
            prop: 'name',
            search: true
          },
          {
            label: '日历编码',
            prop: 'code',
            search: true
          },
          {
            label: '作业时间方案',
            prop: 'defaultWorkingDay',
            formatter: (row) => {
              let defaultWorkingDay = JSON.parse(row.defaultWorkingDay || '{}');
              return defaultWorkingDay.schemeName;
            }
          },
          {
            label: '使用工段',
            prop: 'sectionNames',
            overHidden: true
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.btn {
  padding: 9px 15px;
  font-size: 10px;
  height: 35px;
  background-color: #409eff !important;
  color: #cccccc !important;
}

.is-disabled {
  background-color: #fff !important;
  color: #cccccc !important;
}

.title {
  color: #000;
}

.title:hover {
  color: #000;
}

.search-container {
  display: flex;
  justify-content: space-between;
}

.search-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.el-color-picker__trigger {
  height: 35px;
  width: 35px;
}
::v-deep .addSectionDialog {
  margin-top: 3vh !important;
  .el-dialog__body {
    padding: 0 10px 10px 10px;
    .sectionArea {
      height: 70vh;
      overflow-y: scroll;
      padding-right: 10px;
      .dispatch-title {
        display: flex;
        align-items: center;
        margin: 8px 0;
        &-dot {
          background-color: rgb(102, 177, 255);
          width: 10px;
          height: 20px;
          margin-right: 8px;
        }
        &-text {
          font-weight: bold;
          font-size: 16px;
        }
      }
      .weekdayItem {
        display: flex;
        border: 1px solid #ccc;
        margin-bottom: 10px;
        padding: 8px 0;
        .weekday {
          display: flex;
          align-items: center;
          width: 50%;
          padding: 0 5px;
          box-sizing: border-box;
          .weekday-label {
            height: 32px;
            line-height: 32px;
            width: 120px;
            padding-right: 10px;
            text-align: right;
            vertical-align: middle;
            font-size: 14px;
            color: #606266;
            box-sizing: border-box;
          }
        }
        .workHour {
          display: flex;
          align-items: center;
          padding: 0 5px;
          box-sizing: border-box;
          .workHour-label {
            height: 32px;
            line-height: 32px;
            width: 120px;
            padding-right: 10px;
            text-align: right;
            vertical-align: middle;
            font-size: 14px;
            color: #606266;
            box-sizing: border-box;
          }
          .hour {
            height: 32px;
            line-height: 32px;
          }
        }
      }
      .avue-form__menu {
        display: none;
      }
    }
  }
}

::v-deep .selectLineDialog {
  .el-dialog__body {
    padding: 10px;
    .selectLineArea {
      display: flex;
      align-items: center;
      .leftCrud {
        width: 40%;
      }
      .rightCrud {
        width: 40%;
        .avue-crud__search {
          visibility: hidden;
        }
      }
      .el-transfer-button {
      }
    }
  }
}
</style>
